import os
import yaml
import pymysql

from Utils.logger import Log

# 接受logger实例
getLogger = Log("mysql")
log = getLogger.get_log()

#读取mysql
class sqlConnect:
    def __init__(self):
        try:
            self.db = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='loginTest', charset='utf8')
            log.info("mysql连接成功!!!")
        except Exception as e:
            log.error("mysql连接失败!!"+str(e))

    #查询操作
    def selectLoginInfo(self, sel):
        data = None
        try:
            cursor = self.db.cursor()       # 使用 cursor() 方法创建一个游标对象 cursor
            rowNum = cursor.execute(sel)    # 返回影响行数
            data = cursor.fetchall()
            log.info("success!! 查询影响行数%ds 查询mysql的登录账号信息成功" % rowNum)
        except Exception as e:
            log.error("查询失败: "+str(e))
        finally:
            self.db.close()

        return data

    # 增 删 改 操作
    def updateLoginInfo(self, sql):
        try:
            self.cursor = self.db.cursor()           # 使用 cursor() 方法创建一个游标对象 cursor
            affectedRowsNum = 0
            for sql in sql:
                self.cursor.execute(sql)      # 修改   返回影响行数
                affectedRowsNum += 1
            self.cursor.execute("commit")
            log.info("成功了,影响行数为"+str(affectedRowsNum))
            return True
        except Exception as e:
            bool = False
            self.cursor.execute("rollback")
            print("修改失败: "+str(e))
        finally:
            self.db.close()

#读取yaml文件
class YamlReader:
    def __init__(self, yamlf):
        if os.path.exists(yamlf):
            self.yamlf = yamlf
        else:
            raise FileNotFoundError('文件不存在！ 或文件路径有问题 ')
        self._data = None

    @property
    def data(self):
        # 如果是第一次调用data，读取yaml文档，否则直接返回之前保存的数据
        if not self._data:
            file = open(self.yamlf, "r", encoding="UTF-8")
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data
        return self._data
#data = yaml.load(file, Loader=yaml.FullLoader)
# self._data = list(yaml.safe_load_all(f))  # load后是个generator，用list组织成列表


if __name__ == "__main__":
    load_yaml = YamlReader("../Data/login.yaml")
    kk = load_yaml.data   #返回list
    print(kk)

    db = sqlConnect()
    db.updateLoginInfo(["delete from user_pass where username='1'"])
